package com.hxwb.robot.controller;

import com.hxwb.robot.entity.RobotEntity;
import com.hxwb.robot.request.RobotReq;
import com.hxwb.robot.response.RobotRes;
import com.hxwb.robot.robotEnum.StatusEnum;
import com.hxwb.robot.service.RobotService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/robot")
public class RobotController {
    @Autowired
    private RobotService robotService;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/addRobot")
    public String addRobot(@RequestBody RobotReq robotReq) {
        RobotEntity robotEntity = new RobotEntity();
        BeanUtils.copyProperties(robotReq, robotEntity);
        return robotService.addRobot(robotEntity);
    }

    @GetMapping("/getRobotList")
    public List<RobotRes> getRobotList() {
        return robotService.getRobotList();
    }

    @GetMapping("/startRobot")
    public String startRobot(@RequestParam("id") Integer id) {
        RobotEntity robotEntity = robotService.getOne(id);
        if (null != robotEntity) {
            if (robotEntity.getStatus() == 2) {
                return "该机器人已开启";
            }
            robotEntity.setStatus(2);
            robotService.update(robotEntity);
            robotService.startRobot(robotEntity);
            return "开启成功！";
        }

        return "该机器人不存在";
    }


    @GetMapping("/deleteRobot")
    public String deleteRobot(@RequestParam("id") Integer id) {
        System.out.println("开启robot");
        RobotEntity robotEntity = robotService.getOne(id);
        if (null == robotEntity) {
            return "该机器人不存在";
        }
        redisTemplate.opsForValue().set(robotEntity.getRobotNo(), StatusEnum.STOP.getStatus());//先关闭该机器人
        robotService.delete(id);
        return "删除成功";
    }

    @GetMapping("/stopRobot")
    public String stop(@RequestParam("id") Integer id) {
        System.out.println("关闭robot");
        RobotEntity robotEntity = robotService.getOne(id);
        if (null == robotEntity) {
            return "该机器人不存在";
        }
        robotEntity.setStatus(1);
        robotService.update(robotEntity);
        redisTemplate.opsForValue().set(robotEntity.getRobotNo(), StatusEnum.STOP.getStatus());
        return "关闭成功！";
    }

}
